﻿using Flurl.Http;
using Microsoft.Extensions.Logging;
using SKIT.FlurlHttpClient;
using System.Text.Json;

namespace AiQiuQuan.Sport.Core
{
    /// <summary>
    /// FlurlHttp 日志
    /// </summary>
    internal class FlurlHttpLoggingInterceptor : FlurlHttpCallInterceptor
    {
        private readonly ILogger _logger;
        private readonly JsonSerializerOptions _jsonOptins;

        /// <summary>
        /// ctor
        /// </summary>
        public FlurlHttpLoggingInterceptor(ILogger logger)
        {
            _logger = logger;
            _jsonOptins = new JsonSerializerOptions { WriteIndented = false, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
        }

        public override Task BeforeCallAsync(FlurlCall flurlCall)
        {
            return Task.CompletedTask;
        }

        public override async Task AfterCallAsync(FlurlCall flurlCall)
        {
            try
            {
                var dic = new Dictionary<string, object>();
                var header = new Dictionary<string, string>();
                foreach (var item in flurlCall.Request.Headers)
                {
                    header.TryAdd(item.Name, item.Value);
                }

                foreach (var item in flurlCall.Response.Headers)
                {
                    header.TryAdd(item.Name, item.Value);
                }

                dic.TryAdd("wechat", 1);
                dic.TryAdd("url", flurlCall.Request.Url);
                dic.TryAdd("header", header);
                dic.TryAdd("body", flurlCall.RequestBody);
                dic.TryAdd("response", await flurlCall.HttpResponseMessage.Content.ReadAsStringAsync());
                _logger.LogInformation(JsonSerializer.Serialize(dic, _jsonOptins).Replace(@"\", ""));
            }
            catch { }
        }
    }
}
